import { _decorator, Component, Node, Vec3, Quat, v3, quat } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('FollowAttach')
export class FollowAttach extends Component {
    public originalParent: Node | null = null;
    @property(Node)
    public targetNode: Node | null = null;

    @property
    defaultAttack = false;

    private attached: boolean = false;

    position: Vec3 = v3();
    rotation: Quat = quat();
    scale: Vec3 = v3();

    protected __preload(): void {
        this.position = this.node.position;
        this.rotation = this.node.rotation;
        this.scale = this.node.scale;
    }

    protected onLoad(): void {
        this.originalParent = this.node.parent;
        if (this.targetNode && this.defaultAttack) {
            this.attachTo(this.targetNode);
        }
    }

    /**
     * 将当前节点视觉上附着到目标节点，但保持 transform 不变
     * @param target 目标节点（模拟挂载的父节点）
     */
    public attachTo(target: Node) {
        if (this.attached) return;

        this.originalParent = this.node.parent;
        this.targetNode = target;

        this.attached = true;

        this._attachTarget();

        this.targetNode.on(
            Node.EventType.TRANSFORM_CHANGED,
            this._attachTarget,
            this,
        );
    }

    /**
     * 恢复原始父节点，并保持 transform 不变
     */
    public detach() {
        if (!this.attached || !this.originalParent) return;

        const worldPos = this.node.worldPosition.clone();
        const worldRot = this.node.worldRotation.clone();
        const worldScale = this.node.worldScale.clone();

        this.node.setParent(this.originalParent);

        this.node.setWorldPosition(worldPos);
        this.node.setWorldRotation(worldRot);
        this.node.setWorldScale(worldScale);

        this.attached = false;
        this.targetNode = null;
    }

    /**
     * 每帧同步 transform 到目标节点位置，但保持世界 transform（可视一致）
     */
    // lateUpdate() {
    //     // this._attachTarget();
    // }

    private _attachTarget() {
        if (!this.attached || !this.targetNode) return;

        // 保存世界变换
        const worldPos = this.targetNode.worldPosition.clone();
        const worldRot = this.targetNode.worldRotation.clone();
        const worldScale = this.targetNode.worldScale.clone();

        // 恢复视觉状态
        this.node.setWorldPosition(worldPos);
        this.node.setWorldRotation(worldRot);
        this.node.setWorldScale(worldScale);
    }
}
